package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private WmNewsService wmNewsService;

    /**
     * 查询所有频道
     *
     * @return ResponseResult
     */
    @Override
    public ResponseResult findAll() {
        return ResponseResult.okResult(list());
    }

    /**
     * 频道名称模糊分页查询
     *
     * @param dto :
     * @return ResponseResult
     */
    @Override
    public ResponseResult findByNameWithPage(ChannelDto dto) {
        //1.校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.构建分页条件
        IPage page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmChannel> wrapper = Wrappers.<WmChannel>lambdaQuery();

        //2.1按照频道名称模糊查询
        if (dto.getName() != null) {
            wrapper.like(WmChannel::getName, dto.getName());
        }
        //2.2查询需要按照创建时间倒序查询
        wrapper.orderByDesc(WmChannel::getCreatedTime);
        //2.3可以按照状态进行精确查找（1：启用  true  0：禁用 false）
        //前端没传相关参数，暂时不写

        //2.4分页查询
        page(page, wrapper);

        //4.封装返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 新增频道
     *
     * @param wmChannel :
     * @return ResponseResult
     */
    @Override
    public ResponseResult insert(WmChannel wmChannel) {
        //1.参数校验
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.频道名词不能重复
        //2.1先去数据库查询
        WmChannel channel = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, wmChannel.getName()));
        if (channel != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "频道名词: " + wmChannel.getName() + " 已存在!");
        }

        //2.2新增
        //修改时间
        wmChannel.setCreatedTime(new Date());
        save(wmChannel);
        //3.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 修改频道
     *
     * @param wmChannel :
     * @return ResponseResult
     */
    @Override
    public ResponseResult update(WmChannel wmChannel) {
        //1.参数校验
        if (wmChannel == null || wmChannel.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.业务处理//TODO

        //根据id查询数据库频道数据
        WmChannel dbChannel = getById(wmChannel.getId());
        if (!dbChannel.getName().equals(wmChannel.getName()) ) {
            //数据库中频道名词和要修改的名字不同（也就是需要修改频道名词）

            //判断要修改的频道是否已存在
            WmChannel channel = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, wmChannel.getName()));
            //要修改的频道已存在
            if (channel != null ) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "频道名词: " + wmChannel.getName() + " 已存在!");
            }
        }
        //如果频道被引用则不能禁用
        //查询频道是否被文章引用
        int count = wmNewsService.count(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId())
                .eq(WmNews::getStatus, WmNews.Status.PUBLISHED.getCode()));
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL, "频道被引用则不能禁用和修改");
        }
        //3.返回结果
        updateById(wmChannel);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除频道
     *
     * @param id :
     * @return ResponseResult
     */
    @Override
    public ResponseResult delete(Integer id) {
        //1.参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.只有禁用的频道才能删除
        //根据id查询频道
        WmChannel wmChannel = getById(id);
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "频道不存在");
        }
        //2.1频道状态为启用不能删除
        if (wmChannel.getStatus() == true) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道状态为启用不能删除");
        }
        //2.2查询频道是否被文章引用
        int count = wmNewsService.count(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, wmChannel.getId())
                .eq(WmNews::getStatus, WmNews.Status.PUBLISHED.getCode()));
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL, "频道被引用则不能删除");
        }
        //3.返回结果
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}